#include <stdio.h>
#include <stdlib.h>
#include "jpeglib.h"

//图像宽度
int width = 640;
//图像高度
int height = 480;
//压缩质量
int quality = 80;

int main(int argc, char **argv)
{
    //打开输入文件
    FILE *input = fopen(argv[1], "rb");
    if (!input)
    {
        perror("input file");
        return EXIT_FAILURE;
    }
    //打开输出文件
    FILE *output = fopen(argv[2], "wb");
    if (!output)
    {
        perror("output file");
        return EXIT_FAILURE;
    }
    //JPEG compression object
    struct jpeg_compress_struct cinfo;
    //JPEG error handler
    struct jpeg_error_mgr jerr;
    //set up the error handler
    cinfo.err = jpeg_std_error(&jerr);
    //initialize the JPEG compression object
    jpeg_create_compress(&cinfo);
    //将编码之后的图像写入文件
    //写入内存可以用jpeg_mem_dest函数
    jpeg_stdio_dest(&cinfo, output);
    //压缩图像大小
    cinfo.image_width = width;
    cinfo.image_height = height;
    //每像素字节数
    cinfo.input_components = 3;
    //使用YCbCr颜色空间
    cinfo.in_color_space = JCS_YCbCr;
    //设置默认压缩参数
    jpeg_set_defaults(&cinfo);
    //设置压缩质量
    jpeg_set_quality(&cinfo, quality, TRUE);
    //开始压缩
    jpeg_start_compress(&cinfo, TRUE);

    JSAMPROW jrow;
    unsigned char row[width * 2];
    unsigned char buf[width * 3];
    while (cinfo.next_scanline < cinfo.image_height)
    {
        //每次从输入文件中读取一行像素，即width * 2个字节
        fread(row, sizeof(row), 1, input);
        //将每个像素由YUV422转为YUV444
        for (int i = 0; i < cinfo.image_width; i += 2)
        {
            //Y0U0 Y1V1 Y2U2 Y3V3
            buf[i * 3] = row[i * 2];         //Y0 = Y0
            buf[i * 3 + 1] = row[i * 2 + 1]; //U0 = U0
            buf[i * 3 + 2] = row[i * 2 + 3]; //V0 = V1
            buf[i * 3 + 3] = row[i * 2 + 2]; //Y1 = Y1
            buf[i * 3 + 4] = row[i * 2 + 1]; //U1 = U0
            buf[i * 3 + 5] = row[i * 2 + 3]; //V1 = V1
        }
        jrow = (JSAMPROW)&buf;
        jpeg_write_scanlines(&cinfo, &jrow, 1);
    }
    //停止压缩
    jpeg_finish_compress(&cinfo);
    //释放内存
    jpeg_destroy_compress(&cinfo);
    //关闭文件
    fclose(input);
    fclose(output);
    return 0;
}
